// 设备控制验证逻辑模块

import { DeviceControlRules } from '../device/DeviceControlRules';

interface ValidationResult {
  valid: boolean;
  errorCode?: number;
  errorMessage?: string;
}

/**
 * 检查属性值是否合法：
 * - 属性是否存在于该设备类型规则中
 * - 值是否符合枚举 / 范围
 * - 值类型是否匹配
 */
export function validateControlValue(
  type: string,
  operation: string,
  value: any
): ValidationResult {
  const rules = DeviceControlRules[type];
  // 属性存在情况二次校验
  if (!rules || !rules[operation]) {
    return { valid: false, errorCode: 1002, errorMessage: '属性不存在或不支持' };
  }

  const rule = rules[operation];

  // 类型校验
  switch (rule.type) {
    case 'int':
      if (!Number.isInteger(value)) {
        return { valid: false, errorCode: 1003, errorMessage: '应为整数' };
      }
      break;

    case 'float':
      if (typeof value !== 'number') {
        return { valid: false, errorCode: 1003, errorMessage: '应为数值' };
      }
      if (rule.precision) {
        const precisionFactor = Math.pow(10, rule.precision);
        const rounded = Math.round(value * precisionFactor) / precisionFactor;
        if (Math.abs(rounded - value) > 1e-6) {
          return {
            valid: false,
            errorCode: 1003,
            errorMessage: `小数应保留 ${rule.precision} 位`
          };
        }
      }
      break;

    case 'bool':
      if (typeof value !== 'boolean') {
        return { valid: false, errorCode: 1003, errorMessage: '应为布尔值 true/false' };
      }
      break;

    case 'string':
      if (typeof value !== 'string') {
        return { valid: false, errorCode: 1003, errorMessage: '应为字符串' };
      }
      break;

    default:
      return { valid: false, errorCode: 1003, errorMessage: '未知类型配置' };
  }

  // 枚举校验
  if (rule.enum && !rule.enum.includes(value)) {
    return { valid: false, errorCode: 1003, errorMessage: '属性值不在允许列表中' };
  }

  // 范围校验
  if (rule.range) {
    const [min, max] = rule.range;
    if (value < min || value > max) {
      return {
        valid: false,
        errorCode: 1003,
        errorMessage: `属性值应在 ${min} ~ ${max} 范围内`
      };
    }
  }

  return { valid: true };
}




